package com.tbb.app.common.service.impl;

import com.tbb.app.common.entity.UserInfo;
import com.tbb.app.common.exception.BusinessException;
import com.tbb.app.common.service.CurrentLoginUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * @author LiuSenLin
 * @date 2020/1/16
 */
@Service
public class CurrentLoginUserServiceImpl implements CurrentLoginUserService {

    private static final String CURRENT_USER_NULL_MESSAGE = "未获取到当前用户信息";

    private static final ThreadLocal<UserInfo> currentUserInfo = new ThreadLocal<>();

    private static final ThreadLocal<String> currentAccessToken = new ThreadLocal<>();

    @Override
    public UserInfo getUserInfo() {
        return getUserInfo(false);
    }

    @Override
    public void setUserInfo(UserInfo info) {
        currentUserInfo.set(info);
    }

    @Override
    public String getUserId() {
        return getUserId(false);
    }

    @Override
    public String getAccount() {
        return getAccount(false);
    }

    @Override
    public String getAccessToken() {
        return getAccessToken(false);
    }

    @Override
    public void setAccessToken(String accessToken) {
        currentAccessToken.set(accessToken);
    }

    @Override
    public UserInfo getUserInfo(boolean throwException) {
        UserInfo userInfo = currentUserInfo.get();
        if (throwException && userInfo == null) {
            throw new BusinessException(CURRENT_USER_NULL_MESSAGE);
        }
        return userInfo;
    }

    @Override
    public String getUserId(boolean throwException) {
        UserInfo userInfo = getUserInfo(throwException);
        if (throwException && (userInfo == null || StringUtils.isEmpty(userInfo.getId()))) {
            throw new BusinessException(CURRENT_USER_NULL_MESSAGE);
        } else if (userInfo == null || StringUtils.isEmpty(userInfo.getId())) {
            return "";
        } else {
            return userInfo.getId();
        }
    }

    @Override
    public String getAccount(boolean throwException) {
        UserInfo userInfo = getUserInfo(throwException);
        if (throwException && (userInfo == null || StringUtils.isEmpty(userInfo.getAccount()))) {
            throw new BusinessException(CURRENT_USER_NULL_MESSAGE);
        } else if (userInfo == null || StringUtils.isEmpty(userInfo.getAccount())) {
            return "";
        } else {
            return userInfo.getAccount();
        }
    }

    @Override
    public String getAccessToken(boolean throwException) {
        String accessToken = currentAccessToken.get();
        if (throwException && StringUtils.isEmpty(accessToken)) {
            throw new BusinessException(CURRENT_USER_NULL_MESSAGE);
        }
        return accessToken;
    }

    @Override
    public void removeUserInfo() {
        currentUserInfo.remove();
        currentAccessToken.remove();
    }
}
